﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using Web.Framework.Config;
using Web.PuntoDeVenta.Code;
using Web.Framework;
using System.Web.Security;
using CrmContacto.Contracts.Contracts;
using System.Text;
using Web.Framework.Svc;
using CrmContacto.Contracts.Contracts.Search;

namespace Web.PuntoDeVenta.Account
{
    public partial class Login : BasePage
    {       
        protected void Page_Load(object sender, EventArgs e)
        {
            masterPage.MakeMenuVisible(false);

            List<string> cookieCompany = HttpHelper.GetCookieValues(HttpHelper.cookieCompany, this.Request);
            List<string> cookiePtoVta = HttpHelper.GetCookieValues(HttpHelper.cookiePtoVtaName, this.Request);

            RegisterCompaniesIntoJS();

            bool showPtoVta = cookieCompany.Count > 1 && cookiePtoVta.Count > 1;
            if (showPtoVta)
            {
                int companyId = Convert.ToInt32(cookieCompany[0]);
                var ptoVta = GetPuntoDeVentaCurrent(companyId, false);
                if (ptoVta != null)
                {
                    this.lblPtoVtaInfo.Text = ptoVta.DisplayName;
                    hidPtoVta.Value = cookiePtoVta[0];
                }
                else
                {
                    showPtoVta = false;
                }
            }
            
            if(!showPtoVta)
            {
                this.lblPtoVtaInfo.Text = "Punto de Venta no seleccionado";
                hidPtoVta.Value = string.Empty;
            }

            if (!this.IsPostBack)
            {
                //RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
                //LoginUser.Authenticate += new AuthenticateEventHandler(LoginUser_Authenticate);

                ApiAuthConfigurationSection configuration = (ApiAuthConfigurationSection)ConfigurationManager.GetSection("ApiAuthConfigurationGroup/ApiAuthSecurityConfiguration");

                BaseWebPage.ApplicationId = configuration.ApplicationId;
                BaseMasterPage.ApplicationId = configuration.ApplicationId;
                
                UIHelper.LoadCbo(WebServiceHelper.GetCompanies(BaseWebPage.ApplicationId), cboCompany, "Sin Especificar", value: "Name");

                // Selecciono la empresa en base a la cookie

                if (cookieCompany.Count > 0)
                {
                    this.cboCompany.SelectedValue = cookieCompany[0];                    
                }

                LoadComboPtoVtas();
            }            
        }

        private void RegisterCompaniesIntoJS()
        {
            // Tengo que registrar el array en javascript
            StringBuilder builder = new StringBuilder();
            string separador = string.Empty;
            builder.Append("<script type='text/javascript' >");
            builder.Append("var companies = [];");
            foreach (CompanyConfiguration companyConfiguration in BasePage.GetCompanyConfigurationList(this.Page))
            {
                builder.AppendFormat("companies[{0}] = '{1}##{2}';", companyConfiguration.CompanyId, companyConfiguration.LogoImgFilePath, companyConfiguration.CssFilePath);
                //builder.AppendFormat("companies[{0}] = '{1}';", companyConfiguration.CompanyId, companyConfiguration.LogoImgFilePath);
            }

            builder.Append("</script>");
            Page.ClientScript.RegisterStartupScript(typeof(string), "companias", builder.ToString());
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                //var ctrl = (DropDownList)this.LoginUser.FindControl("CompanyCbo");
                ApiAuthConfigurationSection configuration = (ApiAuthConfigurationSection)ConfigurationManager.GetSection("ApiAuthConfigurationGroup/ApiAuthSecurityConfiguration");
                bool isAutenticated = false;

                // Agrego la cookie para el combo de punto de ventas     
                HttpHelper.SetCookieValues(HttpHelper.cookieCompany, this.Response, cboCompany.SelectedValue, cboCompany.SelectedItem.Text);

                var puntosDeVentaList = GetPuntosDeVentaDto(Convert.ToInt32(cboCompany.SelectedValue));                
                var ptoVta = puntosDeVentaList.Where(p => p.Id.ToString() == this.Request.Form[cboPtoVta.UniqueID]).Single();
                HttpHelper.SetCookieValues(HttpHelper.cookiePtoVtaName, this.Response, ptoVta.Id.ToString(), ptoVta.Nombre);
                PuntoDeVentaCurrentSession = ptoVta;

                if (txtUserName.Text == configuration.SuperAdminName && txtPassword.Text == configuration.SuperAdminPassword)
                {
                    isAutenticated = true;
                    BaseMasterPage.IsAdmin = true;
                }
                else if (WebServiceHelper.Authenticate(BaseWebPage.ApplicationId, Convert.ToInt32(cboCompany.SelectedValue), txtUserName.Text, txtPassword.Text))
                {
                    isAutenticated = true;
                    BaseMasterPage.IsAdmin = false;                   
                }
                else
                {
                    // informar el error
                    this.masterPage.ShowMessage("El usuario o password es incorrecto", WebMessageType.Notification);
                }

                if (isAutenticated)
                {
                    BaseMasterPage.CompanyId = Convert.ToInt32(cboCompany.SelectedValue);
                    BaseWebPage.CompanyId = BaseMasterPage.CompanyId;
                    BaseMasterPage.UserName = txtUserName.Text;

                    Session["Marca"] = Marca.GetMarca(BaseMasterPage.CompanyId);

                    // seteo el nombre del usuario en el login
                    string displayName = txtUserName.Text;
                    var adUser = WebServiceHelper.GetUsers(BaseWebPage.ApplicationId, BaseMasterPage.CompanyId, txtUserName.Text).SingleOrDefault();
                    if (adUser != null)
                    {
                        if (!String.IsNullOrEmpty(adUser.GivenName))
                        {
                            displayName = adUser.GivenName;
                        }
                    }

                    BaseWebPage.DisplayUserName = displayName;

                                                                                     
                    FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void LoadComboPtoVtas()
        {            
            if (cboCompany.SelectedIndex >= 0)
            {
                int empresaId = Convert.ToInt32(cboCompany.SelectedValue);
                if (empresaId.ToString() != UIHelper.cboNullValue)
                {
                    var puntosDeVentaList = WebServiceHelper.GetPuntoDeVentaDto(new ServiceOptions(), new PuntoDeVentaSearch() { EmpresaId = empresaId, Activo = true });
                    //var puntosDeVentaList = GetPuntosDeVentaDto(empresaId);

                    //foreach (var ptoVta in puntosDeVentaList)
                    //{
                    //    ptoVta.Nombre = ptoVta.Nombre;
                    //}

                    UIHelper.LoadCbo(puntosDeVentaList, cboPtoVta, string.Empty);
                    // Preselecciono el combo
                    string ptoVentaSelected = hidPtoVta.Value;
                    if (!String.IsNullOrEmpty(ptoVentaSelected))
                    {
                        if (puntosDeVentaList.Where(l => l.Id.ToString() == ptoVentaSelected).Count() > 0)
                        {
                            this.cboPtoVta.SelectedValue = ptoVentaSelected; // ver de poner un try por si falla al no estar el valor
                        }
                    }
                }
            }
        }        
    }
}
